// pages/my-company/my-company.js
const app = getApp();
const db = wx.cloud.database().collection("company")
Page({

  /**
   * 页面的初始数据
   */
  data: {
    cname:'',
    imgUrl:'',
    cauthen:0
  },
  onLoad: function (options) {
    wx.cloud.database().collection("user").where({
      _openid: app.globalData.user_openid 
    }).get().then(res => {
      if (res.data && res.data.length > 0) {
        const userInfo = res.data[0];
        this.setData({ 
          cauthen: userInfo.cauthen });
  
        if (userInfo.cauthen === 1 || userInfo.cauthen === 2 || userInfo.cauthen === 3) {
          console.log(app.globalData.user_openid)
          db.where({
            _openid: app.globalData.user_openid 
          }).get().then(res => {
            if (res.data && res.data.length > 0) {
              const auditInfo = res.data[0];
              // Update the data to be displayed on the page
              this.setData({
                cname: auditInfo.cname,
                imgUrl: auditInfo.purl
              });
            }
          }).catch(err => {
            console.error('查询审核信息失败：', err);
          });
        }
      }
    }).catch(err => {
      console.error('查询用户信息失败：', err);
    });
  },
  handleUpload() {
    let that = this;
    let timestamp = (new Date()).valueOf();
    wx.chooseImage({
     success: chooseResult => {
      wx.showLoading({
       title: '上传中',
      })
      // 将图片上传至云存储空间
      wx.cloud.uploadFile({
       // 指定上传到的云路径
       cloudPath: 'company/'+timestamp + '.png',
       // 指定要上传的文件的小程序临时文件路径
       filePath: chooseResult.tempFilePaths[0],
       // 成功回调
       success: res => {
        console.log('上传成功', res)
        wx.hideLoading()
        wx.showToast({
         title: '上传图片成功',
        })
        if (res.fileID) {
         that.setData({
          zhaopian: '图片如下',
          imgUrl: res.fileID
         })
        }
  
       },
      })
     },
    })
    },
    submit() {
      const { cname, imgUrl } = this.data;
    
      if (!cname || !imgUrl) {
        wx.showToast({
          title: '请填写完整信息',
          icon: 'error'
        });
        return;
      }
    
      if (this.data.cauthen === 3) {
        db.where({
          _openid: app.globalData.user_openid
        }).update({
          data: {
            cname: cname,
              purl: imgUrl,
              type: 0
          }
        }).then(res => {
          console.log('数据更新成功', res);
          // 更新成功后重新加载页面数据
    
          wx.cloud.database().collection("user").where({
              _openid: app.globalData.user_openid // Assuming you store openid in globalData
            }).update({
              data: {
                cauthen: 1
              }
            }).then(() => {
              console.log('cauthen更新成功');
              this.onLoad();
            }).catch(err => {
              console.error('cauthen更新失败', err);
            });
          wx.showToast({
            title: '提交成功',
            icon: 'success'
          });
        }).catch(err => {
          console.error('数据更新失败', err);
          wx.showToast({
            title: '提交失败，请重试',
            icon: 'none'
          });
        });

      }
      else if (this.data.cauthen === 0) {
      db.where({
        cname: cname
      }).get().then(res => {
        if (res.data.length > 0) {
          const existingData = res.data[0];
          if (existingData.type) {
            wx.showToast({
              title: '信息已被认证过',
              icon: 'none'
            });
          } else {
            wx.showToast({
              title: '该信息正在审核中，请勿重复提交',
              icon: 'none'
            });
          }
        } else {
          
          db.add({
            data: {
              cname: cname,
              purl: imgUrl,
              type: 0
            }
          }).then(res => {
            console.log('数据添加成功', res);
             // After successful submission, update the authen field in the user table
        wx.cloud.database().collection("user").where({
          _openid: app.globalData.user_openid // Assuming you store openid in globalData
        }).update({
          data: {
            cauthen: 1
          }
        }).then(() => {
          console.log('cauthen更新成功');
          this.onLoad();
        }).catch(err => {
          console.error('cauthen更新失败', err);
        });
            wx.showToast({
              title: '提交成功',
              icon: 'success'
            });
          }).catch(err => {
            console.error('数据添加失败', err);
            wx.showToast({
              title: '提交失败，请重试',
              icon: 'none'
            });
          });
        }
      }).catch(err => {
        console.error('查询失败', err);
        wx.showToast({
          title: '查询失败，请重试',
          icon: 'none'
        });
      });
    }
  }
    
})